﻿#include "Double_Linked_List.h"

//创建节点
DoubleList* DoubleList_Apply_Node(DoubleListDataType x)
{
	DoubleList* newnode = (DoubleList*)malloc(sizeof(DoubleList));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode;
	newnode->prev = newnode;
	return newnode;
}

//初始化
void DoubleList_Init(DoubleList** pphead)
{
	//给双向链表创建一个哨兵位
	*pphead = DoubleList_Apply_Node(-1);

}

//尾插
void DoubleList_Push_Back(DoubleList* phead, DoubleListDataType x)
{
	//不能是空指针
	assert(phead);
	DoubleList* newnode = DoubleList_Apply_Node(x);
	//先修改新的节点
	newnode->prev = phead->prev;
	newnode->next = phead;
	//再修改链表
	phead->prev->next = newnode;
	phead->prev = newnode;

}

//头插
void DoubleList_Push_Front(DoubleList* phead, DoubleListDataType x)
{
	assert(phead);
	DoubleList* newnode = DoubleList_Apply_Node(x);
	//先修改新的节点
	newnode->prev = phead;
	newnode->next = phead->next;

	phead->next->prev = newnode;
	phead->next = newnode;
}

void DoubleList_Print(DoubleList* phead)
{
	DoubleList* pcur = phead->next;
	while (pcur != phead)
	{
		printf(" %d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

//尾删
void DoubleList_Pop_Back(DoubleList* phead)
{
	assert(phead && phead->next != phead);
	
	DoubleList* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;

	free(del);
	del = NULL;
}

//头删
void DoubleList_Pop_Front(DoubleList* phead)
{
	assert(phead && phead->next != phead);
	DoubleList* del = phead->next;

	del->next->prev = phead;
	phead->next = del->next;

	//删除del结点
	free(del);
	del = NULL;

}

//查找指定位置
DoubleList* DoubleList_Find(DoubleList* phead,DoubleListDataType x)
{
	DoubleList* pcur = phead->next;
	while (pcur != phead)
	{

		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}

	return NULL;
}

//在指定位置后加入
void DoubleList_Insert(DoubleList* pos,DoubleListDataType x)
{
	assert(pos);
	DoubleList* newnode = DoubleList_Apply_Node(x);
	newnode->next = pos->next;
	newnode->prev = pos;

	pos->next->prev = newnode;
	pos->next = newnode;
}

//指定位置删除
void DoubleList_Erase(DoubleList* pos)
{
	assert(pos);

	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}

//销毁
void DoubleList_Destroy(DoubleList* phead)
{
	//不能传入空指针
	assert(phead);
	DoubleList* pcur = phead->next;
	while (pcur != phead)
	{
		DoubleList* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}


















































